<template>
<el-dialog :title="dialog.title" :visible.sync="dialog.visible" width="30%">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
        <el-form-item label="地区名称名称" prop="title">
            <el-input v-model="ruleForm.shortname" placeholder="请填写渠道名称"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
            <el-input v-model="ruleForm.sort"></el-input>
        </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
    </div>
</el-dialog>
</template>

<script>
import {
    saveRegionApi
} from "@/api/system/dictionary/region";
import {
    getFormToken
} from "@/api/system/system";

const ruleForm = {
    id: "",
    shortname: "",
    sort: 0,
};

export default {
    data() {
        return {
            dialog: {
                title: "",
                visible: false,
                type: "",
            },
            ruleForm: Object.assign({}, ruleForm),
            rules: {
                shortname: [{
                        required: true,
                        message: "地区名称不能为空",
                        trigger: "blur",
                    },
                    {
                        min: 2,
                        max: 30,
                        message: "长度在 2 到 30 个字符",
                        trigger: "blur",
                    },
                ],
            },
        };
    },
    methods: {
        showSaveView(row) {

            let dialog = {
                title: "编辑地区信息",
                visible: true,
                type: "save",
            };
            this.dialog = dialog;
            // 初始化表单
            let ruleForm = {};
            ruleForm['id'] = row.id;
            ruleForm['shortname'] = row.shortname;
            ruleForm['sort'] = row.sort;

            this.ruleForm = Object.assign({}, ruleForm);
            // 获取表单的token
            getFormToken({
                api: "/api/system.region/save",
            }).then(res => {
                this.ruleForm.form_token = res.data.token;
            });
        },
        submit() {
            this.$refs["ruleForm"].validate((valid) => {
                // 验证失败阻止提交
                if (!valid) return false;
                // 提交表单

                saveRegionApi(this.ruleForm)
                    .then((res) => {
                        if (res.code == "200") {
                            this.dialog.visible = false;
                            this.$emit("getTableData", {});
                            this.$message.success(res.msg);
                        } else {
                            this.$message.error(res.msg);
                        }
                    })
                    .catch((res) => {
                        this.$message.error(res.msg);
                    });

            });
        },
    },
};
</script>
